/**
 *	 defined the main entry program
 *   VisualGroup JavaScript prototype Classes, version draf
 *  (c) 2008 Bill Vison <vison_ruan@126.com>
 *
 *
/*--------------------------------------------------------------------------*/
/**
 *	Thread Class defined.
 *	Running the class
 */
Thread = Ext.extend(Ext.util.Observable ,{
	/** 0-> stop  , 1->ready , 2->running , 3-> sleep , 4->*/				
	_state:0,
	_threadId:0,
	// check the function run
	_ran:0,
	_sleepran:0,

	constructor:function($config) {
		
	
		if ($config != null) {
			// --- check the runnble --- 
			if ($config.runnable.run == null) {
				throw new Thread.ThreadException("did not implement the interface 'run'!" , null , Thread.ThreadException.NotImplementRunnable);
			} else {
				this.addEvents({run:false});
				this.addListener("run" , $config.runnable.run , this ,  {single:false});
			}
		} else {
			this.addEvents({run:true});
		}
		Ext.apply(this, $config);
		
		Thread.superclass.constructor.call(this);
		
		this.on("runHandle",this._runHandle);
		
		// ---- defined the event ---
	
	},
	
	_setId:function($id) {
		this._threadId = $id;
	},
	
	getId:function() {
		return this._threadId;
	},
	
	getState:function() {
		return this._state;
	},
	_setState:function($state) {
		this._state = $state;
	},
	_runHandle:function() {

		if (this.runnable != null) {
			this.fireEvent("run" , this.runnable);
		} else {
			this.fireEvent("run");
		}
		
		this._ran = 1;
		
	},
	/**
	 * defined sleeping method defined
	 */
	sleep:function($fn , $sleepingTime) {
		this._setState( Thread.SLEEP);

		this.addListener("sleep",$fn,this , {single:true,delay:$sleepingTime});
		this.on("afterSleep" , this._afterSleep);

	},
	
	_afterSleep:function() {
		this._state = Thread.RUNNING;
		if (!this.hasListener("sleep")) {
			this._sleepran = 1;
		}
		
	},
	
	start:function() {

		this._setState( Thread.READY );
		
		ThreadsManagerMechanism.addThread(this);
		
	}
});

Thread.STOP = 0;
Thread.READY = 1;
Thread.RUNNING = 2;
Thread.SLEEP = 3;

/**
 * defined the thread common Exception
 */
Thread.ThreadException = Ext.extend(Exception.SysException,{
	name:"Thread.ThreadException",
	constructor:function($message , $name ,$value) {
		Thread.ThreadException.superclass.constructor.apply(this, arguments);
	}
});

Thread.ThreadException.ExecRunError = 1;
Thread.ThreadException.NotImplementRunnable = 3;
